package com.changeover.controller;

import java.util.Collection;
import java.util.Map;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    @RequestMapping("/index")
    public String success(Map<String, Object> map) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username;
        String result = "success";
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
            Collection<GrantedAuthority> coll = ((UserDetails) principal).getAuthorities();
            map.put("success", "success");
            for (GrantedAuthority grantedAuthority : coll) {
                String role = grantedAuthority.getAuthority();
                System.out.println(grantedAuthority.getAuthority());
                if (role.equals("ROLE_MANAGER")) {
                    result = "manager";
                } else if (role.equals("ROLE_TASK")) {
                    result = "task";
                }
            }
        } else {
            username = principal.toString();
            result = "redirect:/login.jsp";
        }
        System.out.println(username);
        return result;
    }

    @RequestMapping("/")
    public String home() {
        return "redirect:/index";
    }

    // @RequestMapping(value = "/", method = RequestMethod.GET)
    // public String home() {
    // return "home";
    // }

    // @RequestMapping(value = "/login", method = RequestMethod.POST)
    // public String login(@RequestParam String login, @RequestParam String password, Map<String,
    // Object> map) {
    // if (loginService.isUserExistent(login, password)) {
    // map.put("username", login);
    // return "success";
    // } else {
    // return "redirect:/";
    // }
    // }
}
